from django import template
from urllib import urlencode

register = template.Library()

PAGINATOR_PAGE_VAR = 'page'
PAGINATOR_PERPAGE_VAR = 'perpage'

@register.inclusion_tag('pagemagic/paginator.html', takes_context=True)
def paginator(context, page,
    arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, arg6=None
):
    adjacent_pages = 5
    # TODO temporary hack. *args doesn't work with register.inclusion_tag (?)
    args = filter(lambda arg: arg is not None, [arg1, arg2, arg3, arg4, arg5, arg6])

    rng = range(page.number - adjacent_pages, page.number + adjacent_pages + 1)
    page_numbers = [n for n in rng if 0 < n <= page.paginator.num_pages]

    if len(page_numbers) <= 1:
        return {'show': False}

    prev_dot, next_dot = None, None
    if len(page_numbers) > 2:
        if page_numbers[0] != 1:
            prev_dot = page_numbers[0] - 1

        if page_numbers[-1] != page.paginator.num_pages:
            next_dot = page_numbers[-1] + 1

    qs = urlencode(dict((args[i], args[i + 1]) for i in xrange(0, len(args), 2)))

    return {
        'show': True,
        'page': page,
        'page_numbers': page_numbers,
        'page_var': PAGINATOR_PAGE_VAR,
        'perpage_var': PAGINATOR_PERPAGE_VAR,
        'prev_dot': prev_dot,
        'next_dot': next_dot,
        'qs': qs and qs + '&' or ''
    }
